﻿Imports System.Collections.Generic
Imports System.Data

Partial Class WebForm_CommonControl_UploadFileControl
    Inherits System.Web.UI.UserControl

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        ScriptManager.GetCurrent(Me.Page).RegisterPostBackControl(Button1)

        'bug
        'MyObj.WriteLog(Me.btnDummy.UniqueID)
        'MyObj.WriteLog(Me.btnOK.UniqueID)
        'MyObj.WriteLog(Me.panel1.UniqueID)


        Me.Visible = False
    End Sub

    '按下刪除 
    Protected Sub lbtnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs)

        Try

            Dim sql As New MyStringBuilder
            Dim dat As New clsData

            sql.AppendFormat("SELECT * ")
            sql.AppendFormat("FROM UploadFiles ")
            sql.AppendFormat("WHERE FileSaveName='{0}' ", GridView1.DataKeys(DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow).RowIndex).Value)

            Dim tmpTable As DataTable = dat.GetData(sql)

            If tmpTable IsNot Nothing AndAlso tmpTable.Rows.Count > 0 Then

                Dim objDataRow As DataRow = tmpTable.Rows(0)

                '刪除檔案 
                Dim FileInfo As New System.IO.FileInfo((Server.MapPath(objDataRow("FileSavePath").ToString()) + objDataRow("FileSaveName").ToString() & ".") + objDataRow("FileType").ToString())
                If FileInfo.Exists Then
                    FileInfo.Delete()
                End If

                '刪除資料 
                'ObjectDataSource1.DeleteParameters("Original_FileSaveName").DefaultValue = objDataRow("FileSaveName").ToString()
                'ObjectDataSource1.DeleteParameters("SessionName").DefaultValue = strClass + strType


                ObjectDataSource1.Delete()

            End If

        Catch ex As Exception
            MyObj.ShowMessage(Me.GetLocalResourceObject("DelateFail"))
        End Try

        Me.Show()

    End Sub

    '下載檔案 
    Protected Sub lbtnDownLoadFile_Click(ByVal sender As Object, ByVal e As EventArgs)

        Dim sql As New MyStringBuilder
        Dim dat As New clsData

        sql.AppendFormat("SELECT * ")
        sql.AppendFormat("FROM UploadFiles ")
        sql.AppendFormat("WHERE FileSaveName='{0}' ", GridView1.DataKeys(DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow).RowIndex).Value)

        Dim tmpTable As DataTable = dat.GetData(sql)

        If tmpTable IsNot Nothing AndAlso tmpTable.Rows.Count > 0 Then

            Dim objDataRow As DataRow = tmpTable.Rows(0)

            Dim FileInfo As New System.IO.FileInfo((Server.MapPath(objDataRow("FileSavePath").ToString()) + objDataRow("FileSaveName").ToString() & ".") + objDataRow("FileType").ToString())

            If FileInfo.Exists Then

                Me.Response.Clear()
                Me.Response.AddHeader("Content-Disposition", ("attachment;filename=" & objDataRow("FileName")))
                Me.Response.HeaderEncoding = System.Text.Encoding.GetEncoding("big5")
                Me.Response.AddHeader("Content-Length", FileInfo.Length.ToString())
                Me.Response.ContentType = "application/octet-stream"
                Me.Response.WriteFile(FileInfo.FullName)
                Me.Response.End()

            End If

        End If

        Me.Show()

    End Sub

    Private Sub SaveUploadFile(ByVal theClass As String, ByVal theType As String, ByVal theFileUpload As FileUpload, ByVal theDesc As String)

        If Me.AllowMultipleUploads = False And Me.GridView1.Rows.Count >= 1 Then
            MyObj.ShowMessage(Me.GetLocalResourceObject("SaveUploadFile_1"))
            Return
        End If

        If Not theFileUpload.HasFile Then
            MyObj.ShowMessage(Me.GetLocalResourceObject("FileFail"))
            Exit Sub

        End If


        Dim strFileLongName As String = theFileUpload.PostedFile.FileName
        Dim strFileName As String = strFileLongName.Substring(strFileLongName.LastIndexOf("\") + 1)
        Dim strFileType As String = strFileName.Substring(strFileName.LastIndexOf(".") + 1)
        Dim strFileShortName As String = strFileName.Substring(0, strFileName.LastIndexOf("."))
        Dim strFileSize As String = theFileUpload.PostedFile.ContentLength.ToString()


        Dim sql As New MyStringBuilder
        Dim dat As New clsData

        sql.AppendFormat("SELECT FilePath ")
        sql.AppendFormat("FROM FileGroup ")
        sql.AppendFormat("WHERE FileGroupID='{0}' ", strClass)

        Dim tmpTable As DataTable = dat.GetData(sql)

        If tmpTable IsNot Nothing AndAlso tmpTable.Rows.Count > 0 Then

            Dim strFileSavePath As String = tmpTable.Rows(0).Item("FilePath")

            Dim guidFileSaveName As Guid = Guid.NewGuid()
            Dim strFileSaveLongName As String = (Server.MapPath(strFileSavePath) + guidFileSaveName.ToString() & ".") + strFileType

            Try
                '將檔案上傳至server 
                theFileUpload.PostedFile.SaveAs(strFileSaveLongName)
                '將檔案上傳至DataTable 
                ObjectDataSource1.InsertParameters("theClass").DefaultValue = theClass
                ObjectDataSource1.InsertParameters("theType").DefaultValue = theType
                ObjectDataSource1.InsertParameters("FileName").DefaultValue = strFileName.Replace("'", "''")
                ObjectDataSource1.InsertParameters("FileShortName").DefaultValue = strFileShortName.Replace("'", "''")
                ObjectDataSource1.InsertParameters("FileType").DefaultValue = strFileType
                ObjectDataSource1.InsertParameters("FileSavePath").DefaultValue = strFileSavePath
                ObjectDataSource1.InsertParameters("FileSaveName").DefaultValue = guidFileSaveName.ToString()
                ObjectDataSource1.InsertParameters("FileDesc").DefaultValue = txtDesc.Text
                ObjectDataSource1.InsertParameters("CreateBy").DefaultValue = Page.User.Identity.Name

                ObjectDataSource1.Insert()

                Dim args As New UploadedEventArgs(guidFileSaveName.ToString(), theClass, theType)
                RaiseEvent Uploaded(Me, args)

            Catch ex As Exception
                If System.IO.File.Exists(strFileSaveLongName) Then
                    System.IO.File.Delete(strFileSaveLongName)
                End If
                MyObj.WriteErrorLog(ex.Message)
                MyObj.ShowMessage(Me.GetLocalResourceObject("UploadFail"))
            End Try

        End If

    End Sub

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        '按下新增 
        SaveUploadFile(strClass, strType, hiFileUpload, txtDesc.Text)
        txtDesc.Text = ""
        'Me.mpUploadFile.Show()

        'Me.GridView1.DataBind()
        'Me.Show()
        'MyObj.ShowMessage("上傳成功")
    End Sub

    Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender

    End Sub

    Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound

        If e.Row.RowType = DataControlRowType.DataRow Then
            ScriptManager.GetCurrent(Me.Page).RegisterPostBackControl(TryCast(e.Row.FindControl("lbtnDownLoadFile"), LinkButton))
        End If

    End Sub

    Protected Sub GridView1_Sorted(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridView1.Sorted
        Me.Show()
    End Sub

 
End Class


Partial Class WebForm_CommonControl_UploadFileControl

    Public Sub InitDataAndShow()

        Me.txtDesc.Text = String.Empty

        If Not isEdit Then

            hiFileUpload.Enabled = False
            Button1.Enabled = False
            btnOK.Enabled = False
            txtDesc.Enabled = False
            GridView1.Columns(0).Visible = False

        End If

        '刪除暫存資料與實際檔案

        Dim sql As New MyStringBuilder
        Dim dat As New clsData

        sql.AppendFormat("SELECT * ")
        sql.AppendFormat("FROM UploadFiles ")
        sql.AppendFormat("WHERE theClass='{0}' and theType='0' and CreateBy='{1}'", strClass, Page.User.Identity.Name)

        Dim tmpTable As DataTable = dat.GetData(sql)

        If tmpTable IsNot Nothing AndAlso tmpTable.Rows.Count > 0 Then

            For Each objDataRow As DataRow In tmpTable.Rows

                Dim FileInfo As New System.IO.FileInfo((Server.MapPath(objDataRow("FileSavePath").ToString()) + objDataRow("FileSaveName").ToString() & ".") + objDataRow("FileType").ToString())

                If FileInfo.Exists Then
                    FileInfo.Delete()
                End If

            Next

        End If

        sql.Length = 0

        sql.AppendFormat("DELETE UploadFiles ")
        sql.AppendFormat("WHERE theClass='{0}' and theType='0' and CreateBy='{1}'", strClass, Page.User.Identity.Name)

        dat.AccData(sql)

        ObjectDataSource1.SelectParameters("theClass").DefaultValue = strClass
        ObjectDataSource1.SelectParameters("theType").DefaultValue = strType

        GridView1.DataSourceID = ObjectDataSource1.ID
        GridView1.DataBind()

        If (IsColse And IsAdmin = False) OrElse IsVolunteerLeader = True Then
            Button1.Enabled = False
            GridView1.Columns(3).Visible = False
        Else

            Button1.Enabled = True
            GridView1.Columns(3).Visible = True
        End If
        Me.Show()
    End Sub

    Protected Sub Show()
        Me.Visible = True
        Me.mpUploadFile.Show()
    End Sub
End Class

Partial Class WebForm_CommonControl_UploadFileControl

#Region "Property"
    Public Property IsVolunteerLeader() As Boolean
        Get
            If ViewState("IsVolunteerLeader") Is Nothing Then
                ViewState("IsVolunteerLeader") = False
            End If
            Return CBool(ViewState("IsVolunteerLeader"))
        End Get
        Set(ByVal value As Boolean)
            ViewState("IsVolunteerLeader") = value
        End Set
    End Property
    Public Property IsAdmin() As Boolean
        Get
            If ViewState("IsAdmin") Is Nothing Then
                ViewState("IsAdmin") = False
            End If
            Return CBool(ViewState("IsAdmin"))
        End Get
        Set(ByVal value As Boolean)
            ViewState("IsAdmin") = value
        End Set
    End Property
    Public Property IsColse() As Boolean
        Get
            Return CBool(ViewState("IsColse"))
        End Get
        Set(ByVal value As Boolean)
            ViewState("IsColse") = value
        End Set
    End Property
    Public Property strClass() As String
        Get
            Return DirectCast(ViewState("strClass"), String)
        End Get
        Set(ByVal value As String)

            ViewState("strClass") = value
        End Set
    End Property

    Public Property strType() As String
        Get
            Return DirectCast(ViewState("strType"), String)
        End Get
        Set(ByVal value As String)

            ViewState("strType") = value
        End Set
    End Property

    Public Property isEdit() As Boolean
        Get
            Return CBool(ViewState("isEdit"))
        End Get
        Set(ByVal value As Boolean)

            ViewState("isEdit") = value
        End Set
    End Property

    Public Property AllowMultipleUploads() As Boolean
        Get
            If ViewState("AllowMultipleUploads") Is Nothing Then
                Return True
            End If

            Return ViewState("AllowMultipleUploads")
        End Get
        Set(ByVal value As Boolean)

            ViewState("AllowMultipleUploads") = value
        End Set
    End Property

    Public Event Uploaded(ByVal sender As Object, ByVal e As UploadedEventArgs)

    Public Class UploadedEventArgs
        Inherits EventArgs

        Public UploadID As String
        Public RecordType As String
        Public RecordID As String

        Public Sub New(ByVal uploadID As String, ByVal recordType As String, ByVal recordID As String)
            Me.UploadID = uploadID
            Me.RecordType = recordType
            Me.RecordID = recordID
        End Sub
    End Class
#End Region

End Class



